
uniform sampler2D fbo_texture;
uniform sampler2D depth_texture;
in vec2 TexCoords;
out vec4 FragmentColor;
 
float gauss(float ordo, int i, int j) {
	return (1.0/(2.0*3.14*pow(ordo, 2.0))*exp(-(pow(i,2.0)+pow(j,2.0))/(2.0*pow(ordo,2.0))));
} 
 
vec3 blur(int s, vec2 texc) {
	
vec3 res = vec3(0.0,0.0,0.0);
float o = 1000.0;
float sum = 0.0;
float pixelsizew = 1.0 / 1024.0;
float pixelsizeh = 1.0 / 600.0;

	for (int i=-s/2; i<s/2;i++) {
		for (int j=-s/2;j<s/2;j++) {
			float coeff = gauss(o,i,j);
			vec2 add = vec2(pixelsizew * i, pixelsizeh * j);
			vec4 temp = texture2D(fbo_texture, (texc + add))*coeff;
			res += temp.xyz;
			sum+=coeff;
			
		}
	}
	
	return res/sum;
	 
}

vec3 blur2(int s, vec2 texc)
{
	float pixelsizew = 1.0 / 1024.0;
	float pixelsizeh = 1.0 / 600.0;
	vec3 res = vec3(0.0, 0.0, 0.0);
	float sum = 0.0;
	
	for(int i = -s/2; i < s/2; i ++)
	{
		for(int j = -s/2; j < s/2; j ++)
		{
			vec2 add = vec2(pixelsizew * i, pixelsizeh * j);
			res += texture2D(fbo_texture, (texc + add)).xyz;
			sum = sum + 1.0;
		}
	}
	return res / sum;
}

bool inCircle(float radius, vec2 center, vec2 point)
{
	float px = (point.x - center.x) * (point.x - center.x);
	float py = (point.y - center.y) * (point.y - center.y);
	if(px + py < radius * radius)
		return true;
	return false;
}

vec3 gatherEnergy(float min, float max, vec2 NewTexCoords)
{
	float pixelsizew = 1.0 / 1024.0;
	float pixelsizeh = 1.0 / 600.0;
	float sum = 0.0;
	vec3 res = vec3(0.0, 0.0, 0.0);
	vec4 SampleHere = texture2D(fbo_texture, NewTexCoords);
	for(float i = min; i <= max; i++)
	{
		for(float j = min; j <= max; j ++)
		{
			vec2 CurrentCoords = NewTexCoords + vec2(i * pixelsizew, j * pixelsizeh);
			vec4 TexSample = texture2D(fbo_texture, CurrentCoords);
			if(inCircle(TexSample.a, CurrentCoords, NewTexCoords) && !(abs(SampleHere.a / TexSample.a) < 0.4 && TexSample.a < 0.0))
			{
//				float coeff = 10.0 / dot((NewTexCoords - CurrentCoords), (NewTexCoords - CurrentCoords));
				res += TexSample.xyz;// * coeff;
				
				sum++;//=coeff;
			}
		}
	}
	return res / sum;
}

void main(void) {
	vec2 NewTexCoords = ((TexCoords) + 1.0) * 0.5;
  

  vec3 TextureSample;
  /*
  if(size > 2)
	TextureSample = blur(size, NewTexCoords);//texture2D(fbo_texture, NewTexCoords);
  else
	TextureSample = DepthSample.xyz;
  */
  
  TextureSample = gatherEnergy(-3.0, 3.0, NewTexCoords);
  vec4 DepthSample = texture2D(fbo_texture, NewTexCoords);
  FragmentColor = vec4(TextureSample, DepthSample.a);	
  //if(FragmentColor.r < 0.3) 
  //FragmentColor = vec4(1.0, 1.0, 1.0, 1.0);
}
